$(function () {
    init();
    function init() {
        eventList();
        load_data();
    }

    function eventList() {
        $('#search_btn').on('tap', function () {
            var search_txt = $('#search_inp').val().trim();
            if (!search_txt) {
                mui.toast('输入非法');
                return;
            }
            //判断localStorage里面是否有值,有的话将json字符串转换为json对象
            var arr = window.localStorage.getItem('lt_history') ? JSON.parse(window.localStorage.getItem('lt_history')) : [];
            arr.forEach(function (value, index) {
                if (value == search_txt) {
                    arr.splice(index, 1);
                }
            });
            arr.unshift(search_txt);
            var arrJson = JSON.stringify(arr);
            window.localStorage.setItem('lt_history', arrJson);
            location.href = './searchList.html?proName=' + search_txt;

        })

        //点击按钮删除搜索历史
        $('.history_contain').on('tap', '.remove_btn',function(){
            var his_val = $('.his_name').html();
            var arr = window.localStorage.getItem('lt_history') ? JSON.parse(window.localStorage.getItem('lt_history')) : [];
            arr.forEach(function (value, index) {
                if (value == his_val) {
                    arr.splice(index, 1);
                    window.localStorage.setItem('lt_history', JSON.stringify(arr));
                    load_data();
                }
            });
        })
        //点击按钮清空搜索历史
        $('#clear_btn').on('tap',function(){
            var arr = window.localStorage.getItem('lt_history') ? JSON.parse(window.localStorage.getItem('lt_history')) : [];
            arr.forEach(function (value, index) {
                // console.log(index);
                // console.log(arr.length);
                    arr.splice(index, arr.length);
                    window.localStorage.setItem('lt_history', JSON.stringify(arr));
                    load_data();
            });
        })
    }

    function load_data() {
        var arr = window.localStorage.getItem('lt_history') ? JSON.parse(window.localStorage.getItem('lt_history')) : [];
        if (arr.length == 0) {
            var html = "没有相关搜索记录...";
            $('.history_contain').html(html);
            return;
        }
        var html = template('mainTemp', { arr: arr });
        $('.history_contain').html(html);
    }
})